(function($) {
	var orderPadding = 0;
    $.fn.windswaterflow = function(options) {
		var v = $(window).width() / 236;//236 为 每个展示商品div的总宽度
		var index_p=0;
        var _init = 0, _isminCols = false, _isnoShow = false;
        var defaults = {
            itemSelector: '',
            loadSelector: '',
            noSelector: '',
            noDataSelector:'',
            boxTemplate: '',
            columnWidth: 222,//每个商品的宽度
            marginWidth: 14,// margin 的宽度
            marginHeight: 16,// margin 的高度
            minCols: 3,//最小列
            maxPage: 0,
            align: 'center',
            ajaxServer: '',
            boxParam: '',
            pageParam: 'page',
            pageTimestamp: 'timestamp',
            pageNumber: 2,
            init: false,
            initBoxNumber: 20,//初始化 商品dive 为20个
            scroll: false,
            scrollBoxNumber: 20//每次滚动加载商品div 为 20个
        };
        var param = $.extend({}, defaults, options || {});
        if (param.itemSelector == '' || param.tplSelector == '') {
            return;
        }
        if (param.noSelector != '') {
            $(param.noSelector).hide();
        }
        if ($(this).css('text-align') != undefined) {
            param.align = $(this).css('text-align');
        }
        function _min(_arr) {
            return Math.min.apply(Math, _arr);
        };
        function _max(_arr) {
            return Math.max.apply(Math, _arr);
        };

        function findShortIndex(_arr) {
            var index = 0, i;
            for (i in _arr) {
                if (_arr[i] < _arr[index]) {
                    index = i;
                }
            }
            return index;
        };

        function findLongIndex(_arr) {
            var index = 0, i;
            for (i in _arr) {
                if (_arr[i] > _arr[index]) {
                    index = i;
                }
            }
            return index;
        };

		
        var _boxCount = $(param.itemSelector).length;// 根据 class = ca 获取到 该商品div 的数量
        var _boxWidth = param.columnWidth + param.marginWidth;//取得商品div 的宽度
        var _containerWidth = $(window).width();
        var _showCols = Math.floor(_containerWidth / _boxWidth);//得到大致展示商品div 的列数
		
		//判断需要的内边距
		var containerWidth = (_boxWidth * _showCols) - 14;
        var containerPadding = (_containerWidth - containerWidth) / 2;//获得网页 商品div 块 于浏览器边 之间的 距离
		
		
        var _tpRows = $(param.itemSelector).length / _showCols;//获得 商品行数
        var _showRows = Math.floor(_tpRows) == _tpRows ? _tpRows : _tpRows + 1;
        var _colsTopArr = [];
        for (var len = 0; len < _showCols; len++) {
            _colsTopArr.push(0);//列数数组
        };

        var selector = $(this).selector;
		//初始化
        if (param.init) {
            $(this).html('');
        }else{
			orderPadding = containerPadding;
			hWidth();//设置头部宽度
			//addClick();// 给所有的商品块 添加事件
			$('.search-result').width($('#cb_header_up').width());
		}
		function hWidth(){
		    var headerWidth = Math.floor(_containerWidth / 236) * 236 - 14;
		    $('#cb_header_up').width(headerWidth);
	    }
		//点击收藏
        var collect = function(c){
        	var _self = $(c);
    		var pid = _self.attr("productid");
    		
    		$.post("/user/operate/addfavorite.do", {pid:pid}, function(rsdata){
    			_self.html('收藏好了').fadeOut(2000);
    		});
        }
        
          //点击 值
        var comments = function(v) {
        	var _self = $(v);
    		var pid = _self.attr("productid");
    		
    		$.post("/user/operate/addworthcount.do", {pid:pid}, function(rsdata){
    			_self.css({'color':'#999'}).animate({opacity:'0.7'},"fast");
    		});
        }
        
	    //点击 不值
	    var comments2 = function(v) {
	    	var _self = $(v);
			var pid = _self.attr("productid");
			
			$.post("/user/operate/addnotworthcount.do", {pid:pid}, function(rsdata){
				_self.css({'color':'#999'}).animate({opacity:'0.7'},"fast");
			});
	    }
	    // 定位商品位置
        function setPosition(wrap, boxs, op) {
            var _tpShortColIdx, _tpLeftPos, _tpTopPos, _tpLen = $(boxs).length;
            
			if (op == "resize" || op == "init") {
                $(wrap).width()
                _isminCols = false;
                _containerWidth = $(wrap).width();
                _showCols = Math.floor(_containerWidth / _boxWidth);
				hWidth();
				
				var a = param.columnWidth + param.marginWidth;
				var c = $(window).width();
				var b = Math.floor(c / _boxWidth);
				var e = (_boxWidth * _showCols) - 14;
				var w = Math.floor($(window).width() / 236) * 236 - 14;
				var f = (c - e) / 2;

                if (_showCols < param.minCols) {
                    orderPadding = f;
                    _showCols = param.minCols;
                    _isminCols = true;
                }
				orderPadding = f;
                _tpRows = $(boxs).length / _showCols;
                _showRows = Math.floor(_tpRows) == _tpRows ? _tpRows : _tpRows + 1;
                _colsTopArr.length = 0;
                for (var len = 0; len < _showCols; len++) {
                    _colsTopArr.push(0);
                };
            }
			
            if (op == null) {
				$(boxs).each(function(index) {
					var _tpShortColIdx = index;
					if (_tpShortColIdx < _showCols && op != "add") {
						_tpLeftPos = _boxWidth * _tpShortColIdx + orderPadding + "px";
						$(this).css({ "top": "0", "left": _tpLeftPos });
					}
					else {
						_tpShortColIdx = findShortIndex(_colsTopArr);
						_tpLeftPos = _boxWidth * _tpShortColIdx + orderPadding + "px";
						_tpTopPos = _colsTopArr[_tpShortColIdx] + "px";
						$(this).css({ "top": _tpTopPos, "left": _tpLeftPos });
					}
					if (op == "add") {
						$(this).appendTo(wrap);
					}
					_colsTopArr[_tpShortColIdx] = _colsTopArr[_tpShortColIdx] + $(this).height() + param.marginHeight;
					if (index == _tpLen - 1) {
						$(wrap).height(_max(_colsTopArr) + "px");
						if (op == "add") {
							if ($.browser.msie) {
								$(".hide").animate({ opacity: 'show' }, 2000);
							}
							else {
								$(".hide").animate({ opacity: 'show' }, 1000);
							}
							if (param.loadSelector != '') {
								$(param.loadSelector).hide();
							}
						}
						_SolStatus = 0;
					}
				});
            }
            else {
                $(boxs).each(function(index) {
                    var _tpShortColIdx = index;
                    if (_tpShortColIdx < _showCols && op != "add") {
                        _tpLeftPos = _boxWidth * _tpShortColIdx + orderPadding + "px";
                        $(this).css({ "top": "0", "left": _tpLeftPos });
                    }
                    else {
                        _tpShortColIdx = findShortIndex(_colsTopArr);
                        _tpLeftPos = _boxWidth * _tpShortColIdx + orderPadding + "px";
                        _tpTopPos = _colsTopArr[_tpShortColIdx] + "px";
                        $(this).css({ "top": _tpTopPos, "left": _tpLeftPos });
                    }
                    if (op == "add" || op == "init") {
                        $(this).appendTo(wrap);//把当前的内容追加到 容器中 this 为当前内容
                    }
                    _colsTopArr[_tpShortColIdx] = _colsTopArr[_tpShortColIdx] + $(this).height() + param.marginHeight;

                    if (index == _tpLen - 1) {
                        $(wrap).height(_max(_colsTopArr) + "px");
                        if (op == "add") {
                            if ($.browser.msie) {
                                $(".hide").animate({ opacity: 'show' }, 2000);
                            }
                            else {
                                $(".hide").animate({ opacity: 'show' }, 1000);
                            }
                        }
                        else {
                            $(".hide").animate({ opacity: 'show' }, 0);
                        }
                        if (param.loadSelector != '') {
                            $(param.loadSelector).hide();
                        }
                        _SolStatus = 0;
                        if (op == "add" || op == "init") {
                            param.pageNumber++;
						}
                    }
                });
            }
			//addClick();
        };

        if (_boxCount > 0) {
            setPosition(selector, param.itemSelector);
			setTimeout(function() {
				$(".ca-flow").fadeIn(1000); 
				$(".ca").fadeIn(1000);
				$('#cb_header_up').css('visibility','visible');
				$('.search-t').css('visibility','visible');
			clearTimeout(this);},'500');
        }else{
        	setTimeout(function() {
				$('#cb_header_up').css('visibility','visible');
				$('.search-t').css('visibility','visible');
			clearTimeout(this);},'500');
        }
        _init = 1;
		
		//为所有商品块 添加事件
		function addClick(){
		    $('.ca').hover(function(){
			    $(this).find('.z-comments').show();
				$(this).find('.commodity-shows').find('.commodity-show').find('.id-collect').show();
				$(this).find('.commodity-shows').find('.zdLink').css('margin-top','-30px').show();
		    },function(){
				$(this).find('.z-comments').hide();
				$(this).find('.commodity-shows').find('.commodity-show').find('.id-collect').hide();
				$(this).find('.commodity-shows').find('.zdLink').hide();
		    })
		    $('.z-comments a').unbind('click');
		    $('.idDeserve').click(function(){
				comments(this);
		    });
		    $('.idNoDeserve').click(function(){
				comments2(this);
		    });
		    $('.id-collect').unbind('click');
		    $('.id-collect').bind('click',function(){
				collect(this);
		    })
		}
		
		//添加商品 块
        function appendBox(data, op) {
            var newBox = [], len = Number(data.length), idx = 0;
            _boxCount += len;
            $.each(data, function(i) {
                //imgReady(data[i].imgUrl, function() {
                    data[i].height = parseInt(this.height);
                    var temp = "";
                    var matchs = param.boxTemplate.match(/\{[a-zA-Z]+\}/gi);
                    for (var j = 0, mlen = matchs.length; j < mlen; j++) {
                        if (temp == "")
                            temp = param.boxTemplate;
                        var re_match = matchs[j].replace(/[\{\}]/gi, "");
                        temp = temp.replace(matchs[j], data[i][re_match]).replace(/[\r\t\n]/g, "");
                    }
                    newBox.push(temp);
                    idx++;
                    if (idx == len) {
                        setPosition(selector, newBox.join(''), op);
                    }
               // });
            });
			//addClick();
        };
		
        //滚动加载
        var _SolStatus = 0;
        if (param.scroll && param.ajaxServer != '' && param.boxParam != '' && parseInt(param.scrollBoxNumber) > 0) {
            $(window).scroll(function() {
                var scrollh = document.body.scrollHeight;//body 元素的滚动高度
                var clienth = document.documentElement.clientHeight;//html 页面的滚动gaodu
                var scrollt = document.documentElement.scrollTop + document.body.scrollTop;
                if (scrollt + clienth >= scrollh -200 && _SolStatus == 0 && _init == 1 && !_isnoShow) {
                    if ((param.maxPage == 0 || param.pageNumber <= param.maxPage)) {						
                        _SolStatus = 1;
                        if (param.loadSelector != '') {
                           // $(param.loadSelector).show();
                        }
                        var postPara = {};
                        postPara[param.boxParam] = parseInt(param.scrollBoxNumber);
                        postPara[param.pageParam] = parseInt(param.pageNumber);
                        postPara[param.pageTimestamp] = parseInt(param.timestamp);
                        setTimeout(function () {
                           // alert("");
                        }, 100);
                    }
                }
            });
        }

        var _ReStatus;
        $(window).wresize(function() {
            if (_ReStatus) {
                clearTimeout(_ReStatus);
            }
            _ReStatus = setTimeout(function() { setPosition(selector, param.itemSelector, "resize"); }, 200);
        });
    };
    var imgReady = (function() {
        var list = [], intervalId = null,
	    tick = function() {
	        var i = 0;
	        for (; i < list.length; i++) {
	            list[i].end ? list.splice(i--, 1) : list[i]();
	        };
	        !list.length && stop();
	    },

	    stop = function() {
	        clearInterval(intervalId);
	        intervalId = null;
	    };

        return function(url, ready, load, error) {
            var onready, width, height, newWidth, newHeight,
			img = new Image();
            img.src = url;
            if (img.complete) {
                ready.call(img);
                load && load.call(img);
                return;
            };

            width = img.width;
            height = img.height;
            img.onerror = function() {
                error && error.call(img);
                onready.end = true;
                img = img.onload = img.onerror = null;
            };

            onready = function() {
                newWidth = img.width;
                newHeight = img.height;
                if (newWidth !== width || newHeight !== height ||
				newWidth * newHeight > 1024
			) {
                    ready.call(img);
                    onready.end = true;
                };
            };
            onready();
            img.onload = function() {
                !onready.end && onready();
                load && load.call(img);
                img = img.onload = img.onerror = null;
            };

            if (!onready.end) {
                list.push(onready);
                if (intervalId === null) intervalId = setInterval(tick, 40);
            };
        };
    })();

    $.fn.imagesLoaded = function(callback) {
        var $this = this,
            $images = $this.find('img').add($this.filter('img')),
            len = $images.length,
            blank = '',
            loaded = [];
        function triggerCallback() {
            callback.call($this, $images);
        }
        function imgLoaded(event) {
            var img = event.target;
            if (img.src !== blank && $.inArray(img, loaded) === -1) {
                loaded.push(img);
                if (--len <= 0) {
                    setTimeout(triggerCallback);
                    $images.unbind('.imagesLoaded', imgLoaded);
                }
            }
        }

        if (!len) {
            triggerCallback();
        }

        $images.bind('load.imagesLoaded error.imagesLoaded', imgLoaded).each(function() {
            var src = this.src;
            this.src = blank;
            this.src = src;
        });
        return $this;
    };

    $.fn.wresize = function(f) {
        version = '1.1';
        wresize = { fired: false, width: 0 };
        function resizeOnce() {
            if ($.browser.msie) {
                if (!wresize.fired) {
                    wresize.fired = true;
                }
                else {
                    var version = parseInt($.browser.version, 10);
                    wresize.fired = false;
                    if (version < 7) {
                        return false;
                    }
                    else if (version == 7) {
                        var width = $(window).width();
                        if (width != wresize.width) {
                            wresize.width = width;
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        function handleWResize(e) {
            if (resizeOnce()) {
                return f.apply(this, [e]);
            }
        }

        this.each(function() {
            if (this == window) {
                $(this).resize(handleWResize);
            }
            else {
                $(this).resize(f);
            }
        });
        return this;
    };
})(jQuery);